# coding=utf-8
import json

import requests
import time

from django.contrib.auth.models import User
from django.http import HttpResponse
from django.http import HttpResponseRedirect
import django.contrib.auth as dj_auth
import Database.models as model
# Create your views here.
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
from django.shortcuts import render_to_response

from WebQuant import deal_interface


def auth(request):
    if 'username' in request.COOKIES:
        username = request.COOKIES['username']
        if username == "":
            return False
        request.session["username"] = username
        request.session["userId"] = username
        return True
    else:
        return False


def index(request):
    if not auth(request):
        return render_to_response('WebQuant/index.html', {"log": 0, "request": request})
    else:
        if 'username' in request.session:
            name = request.session["username"]
            response = render_to_response('WebQuant/index.html', {"log": 1, "name": name, "request": request})
        else:
            response = render_to_response('WebQuant/index.html', {"log": 0, "request": request})
        return response


@ensure_csrf_cookie
def login(request):
    isRegister = request.GET.get('option') 
    if isRegister is None:
	isRegister = 0
    return render_to_response('WebQuant/login.html', {"log": 0, "request": request, "isRegister": int(isRegister),})


@ensure_csrf_cookie
def database(request):
    if auth(request):
        name = request.session["username"]
        response = render_to_response('WebQuant/data_base.html', {"log": 1, "name": name, "request": request})
    else:
        response = render_to_response('WebQuant/data_base.html', {"log": 0, "request": request})
    return response


@ensure_csrf_cookie
def loginjude(request):
    username = request.POST.get('name', '')
    password = request.POST.get('password', '')
    user = dj_auth.authenticate(username=username, password=password)
    if user is not None and user.is_active:
        dj_auth.login(request, user)
        request.session["userId"] = username
        request.session["username"] = username
        response = HttpResponse({'1'})
        response.set_cookie("username", username)
        return response
    else:
        return HttpResponse({'resultCode:': '3051'})


def logout(request):
    request.session.flush()
    response = HttpResponse('logout')
    response.delete_cookie(key='username', path='/')

    return response


@ensure_csrf_cookie
def strategy(request):
    if auth(request):
        name = request.session["username"]
        user_id = request.session["userId"]
        response = render_to_response('WebQuant/strategy.html',
                                      {"log": 1, "name": name, "user_id": user_id, "request": request})
    else:
        response = render_to_response('WebQuant/strategy.html', {"log": 0, "request": request})
    return response


@ensure_csrf_cookie
def management(request):
    if auth(request):
        name = request.session["username"]
        response = render_to_response('WebQuant/management.html', {"log": 1, "name": name, "request": request})
    else:
        response = render_to_response('WebQuant/management.html', {"log": 0, "request": request})
    return response


@ensure_csrf_cookie
def deal(request):
    if auth(request):
        name = request.session["username"]
        deal_list = deal_interface.get_user_deal_list(request)
        response = render_to_response('WebQuant/deal.html',
                                      {"log": 1, "name": name, "request": request, 'deal_list': deal_list})
    else:
        response = render_to_response('WebQuant/deal.html', {"log": 0, "request": request})
    return response


@ensure_csrf_cookie
def deal_del(request):
    if request.method.lower() == 'post':
        del_result = deal_interface.del_deal(request)
        return HttpResponse(json.dumps(del_result))
    else:
        return HttpResponse(json.dumps({'state': 0}))


@ensure_csrf_cookie
def deal_stop(request):
    if request.method.lower() == 'post':
        del_result = deal_interface.stop_deal(request)
        return HttpResponse(json.dumps(del_result))
    else:
        return HttpResponse(json.dumps({'state': 0}))


@ensure_csrf_cookie
def deal_new(request):
    if auth(request):
        name = request.session["username"]

        if request.method.lower() == 'get':
            strategy_list = deal_interface.get_strategy_list_for_new(request)
            response = render_to_response('WebQuant/deal_new.html',
                                          {"log": 1, "name": name, "request": request, 'strategy_list': strategy_list})
        elif request.method.lower() == 'post':
            new_result = deal_interface.new_deal(request)
            return HttpResponse(json.dumps(new_result))
    else:
        response = HttpResponseRedirect('/deal')
    return response


@ensure_csrf_cookie
def deal_new_this(request):
    if auth(request):
        name = request.session["username"]
        if request.method.lower() == 'post':
            new_result = deal_interface.new_deal_this(request)
            return HttpResponse(json.dumps(new_result))
    else:
        response = HttpResponseRedirect('/deal')
    return response


@ensure_csrf_cookie
def deal_back_test(request):
    if auth(request):
        # 获得结果页面
        if request.method.lower() == 'get':
            name = request.session["username"]
            deal_name = request.session.get("deal_name", None)
            deal_info = deal_interface.get_deal_back_test(request)
            response = render_to_response('WebQuant/deal_back_test.html',
                                          {"log": 1, "name": name, "request": request, 'deal_name': deal_name,
                                           'deal_info': deal_info})
        elif request.method.lower() == 'post':
            # 设置为当前结果页
            deal_interface.goto_deal(request)
            # 跳转到结果页
            response = HttpResponse(json.dumps({'state': '0'}))
    else:
        response = HttpResponseRedirect('/deal')
    return response


@ensure_csrf_cookie
def deal_back_test_chart(request):
    if auth(request):
        # 设置为当前结果页
        chart_dict = deal_interface.get_deal_return_chart_detail(request)
        # 跳转到结果页
        response = HttpResponse(json.dumps(chart_dict))
    else:
        response = HttpResponseRedirect('/deal')
    return response


@ensure_csrf_cookie
def deal_daily(request):
    if auth(request):
        name = request.session["username"]
        deal_name = request.session.get("deal_name", None)
        if request.method.lower() == 'get':
            response = render_to_response('WebQuant/deal_daily.html',
                                          {"log": 1, "name": name, "request": request, 'deal_name': deal_name,
                                           })
        elif request.method.lower() == 'post':
            # 获得历史持仓
            position_list = deal_interface.get_deal_position(request)
            response = HttpResponse(json.dumps(position_list))
    else:
        response = HttpResponseRedirect('/deal')
    return response


@ensure_csrf_cookie
def change_deal_name(request):
    if auth(request):
        if request.method.lower() == 'post':
            # 修改当前策略名称
            state = deal_interface.change_deal_name(request)
            response = HttpResponse(json.dumps(state))
    else:
        response = HttpResponseRedirect('/deal')
    return response


@ensure_csrf_cookie
def deal_log(request):
    if auth(request):
        name = request.session["username"]
        deal_name = request.session.get("deal_name", None)
        log_list = deal_interface.get_deal_log(request)
        response = render_to_response('WebQuant/deal_log.html',
                                      {"log": 1, "name": name, "request": request, 'deal_name': deal_name,
                                       'log_list': log_list})
    else:
        response = HttpResponseRedirect('/deal')
    return response


@ensure_csrf_cookie
def deal_code(request):
    if auth(request):
        name = request.session["username"]
        deal_name = request.session.get("deal_name", None)
        src_code = deal_interface.get_strategy_code_for_deal(request)
        response = render_to_response('WebQuant/deal_code.html',
                                      {"log": 1, "name": name, "request": request, 'deal_name': deal_name,
                                       'src_code': src_code})
    else:
        response = HttpResponseRedirect('/deal')
    return response


@ensure_csrf_cookie
def deal_check_deal(request):
    if auth(request):
        if request.method.lower() == 'get':
            status = deal_interface.check_deal(request)
            return HttpResponse(json.dumps(status))
    return HttpResponse('')


@ensure_csrf_cookie
def deal_strategy_status(request):
    if auth(request):
        if request.method.lower() == 'get':
            status = deal_interface.get_deal_strategy_status(request)
            return HttpResponse(json.dumps(status))
    return HttpResponse('')


@ensure_csrf_cookie
def deal_trade_detail(request):
    if auth(request):
        name = request.session["username"]
        deal_name = request.session.get("deal_name", None)
        trade_detail_info = deal_interface.get_deal_trade_info(request)
        response = render_to_response('WebQuant/deal_trade-detail.html',
                                      {"log": 1, "name": name, "request": request, 'deal_name': deal_name,
                                       'trade_detail': trade_detail_info})
    else:
        response = HttpResponseRedirect('/deal')
    return response


@ensure_csrf_cookie
def college(request):
    if auth(request):
        name = request.session["username"]
        response = render_to_response('WebQuant/college.html', {"log": 1, "name": name, "request": request})
    else:
        response = render_to_response('WebQuant/college.html', {"log": 0, "request": request})
    return response


@ensure_csrf_cookie
def research(request):
    if auth(request):
        name = request.session["username"]
        response = render_to_response('WebQuant/research.html', {"log": 1, "name": name, "request": request})
    else:
        response = render_to_response('WebQuant/research.html', {"log": 0, "request": request})
    return response


@ensure_csrf_cookie
def strategy_edit(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    strategyId = request.GET.get('strategyId')
    if strategyId is None:
        strategyId = request.session['strategyId']
        versionId = request.session["versionId"]
    else:
        versionId = request.GET.get('versionId')
        request.session["strategyId"] = strategyId
        request.session["versionId"] = versionId

    queryset = model.UpQuantUserStrategyListInfo.objects.get(strategyid=strategyId)
    context = model.UpQuantStrategyContex.objects.get(strategyid=strategyId, versionid=versionId)
    request.session["strategyName"] = queryset.__dict__["name"]

    return render_to_response('WebQuant/strategyEdit.html',
                              {'name': request.session['username'],
                               'strategyName': request.session["strategyName"],
                               'strategyContext': context.__dict__['context'],
                               'beginDate': str(context.__dict__['begindate']).replace('-', '/'),
                               'endDate': str(context.__dict__['enddate']).replace('-', '/'),
                               'intCash': int(context.__dict__['initcash']),
                               "request": request})


@ensure_csrf_cookie
def history(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/history.html', {'name': request.session['username'],
                                                        'strategyName': request.session["strategyName"],
                                                        "request": request})


@ensure_csrf_cookie
def back_test(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/back-test.html', {'name': request.session['username'],
                                                          'strategyName': request.session["strategyName"],
                                                          "request": request})


@ensure_csrf_cookie
def trade_detail(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/trade-detail.html', {'name': request.session['username'],
                                                             'strategyName': request.session["strategyName"],
                                                             "request": request})


@ensure_csrf_cookie
def daily(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/daily.html', {'name': request.session['username'],
                                                      'strategyName': request.session["strategyName"],
                                                      "request": request})


@ensure_csrf_cookie
def log(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/log.html', {'name': request.session['username'],
                                                    'strategyName': request.session["strategyName"],
                                                    "request": request})


@ensure_csrf_cookie
def earnings(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/earnings.html', {'name': request.session['username'],
                                                         'strategyName': request.session["strategyName"],
                                                         "request": request})


@ensure_csrf_cookie
def alpha(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/alpha.html', {'name': request.session['username'],
                                                      'strategyName': request.session["strategyName"],
                                                      "request": request})


@ensure_csrf_cookie
def beta(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/beta.html', {'name': request.session['username'],
                                                     'strategyName': request.session["strategyName"],
                                                     "request": request})


@ensure_csrf_cookie
def sharpe(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/sharpe.html', {'name': request.session['username'],
                                                       'strategyName': request.session["strategyName"],
                                                       "request": request})


@ensure_csrf_cookie
def sortino(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/sortino.html', {'name': request.session['username'],
                                                        'strategyName': request.session["strategyName"],
                                                        "request": request})


@ensure_csrf_cookie
def inforatio(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/inforatio.html', {'name': request.session['username'],
                                                          'strategyName': request.session["strategyName"],
                                                          "request": request})


@ensure_csrf_cookie
def volatility(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/volatility.html', {'name': request.session['username'],
                                                           'strategyName': request.session["strategyName"],
                                                           "request": request})


@ensure_csrf_cookie
def maxdrawdown(request):
    if not auth(request):
        return HttpResponseRedirect('/strategy')
    return render_to_response('WebQuant/maxdrawdown.html', {'name': request.session['username'],
                                                            'strategyName': request.session["strategyName"],
                                                            "request": request})


@ensure_csrf_cookie
def register(request):
    return render_to_response('WebQuant/mylogin.html', {'isRegister': 1, "request": request})


@ensure_csrf_cookie
def user_register(request):
    cur_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

    # if request.user.is_authenticated():
    # return HttpResponseRedirect("/index")
    try:
        if request.method == 'POST':
            username = request.POST.get('username', '')

            password1 = request.POST.get('password1', '')
            password2 = request.POST.get('password2', '')

            if password1 != password2:
                return HttpResponse({'curTime': cur_time, 'username': username, 'error': 'password not equal'})
            filter_result = model.AuthUser.objects.filter(username=username)
            if len(filter_result.values()) > 0:
                return HttpResponse({'curTime': cur_time, 'username': username, 'error': 'username has been register'})

            user = User()
            user.username = username
            user.set_password(password1)
            user.save()

            return HttpResponse('1')
    except Exception, e:
        print str(e)
        return HttpResponse(str(e))


@ensure_csrf_cookie
def help_api(request):
    try:
        if request.method == 'GET':
            result_list = requests.get('http://192.168.7.250/api/class/list')
            return HttpResponse(result_list.content)
    except Exception, e:
        print str(e)
        return HttpResponse(str(e))
